package com.ruoyi.web.sso.common.util;

import com.ruoyi.web.sso.domain.Menu;
import com.ruoyi.web.sso.domain.vo.MenuList;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MenuUtil {
    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public static List<MenuList> getChildPerms(List<Menu> list, String parentId)
    {
        List<MenuList> lists = new ArrayList<>();
        for (int i = 0; i <list.size() ; i++) {
            MenuList list1 = new MenuList();
            BeanUtils.copyProperties(list.get(i) , list1);
            lists.add(list1);
        }

        List<MenuList> returnList = new ArrayList<MenuList>();
        for (Iterator<MenuList> iterator = lists.iterator(); iterator.hasNext();)
        {
            MenuList t = (MenuList) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (StringUtils.equals(t.getParentId(),parentId))
            {
                recursionFn(lists, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private static void recursionFn(List<MenuList> list, MenuList t)
    {
        // 得到子节点列表
        List<MenuList> childList = getChildList(list, t);
        t.setChildren(childList);
        for (MenuList tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private  static List<MenuList> getChildList(List<MenuList> list, MenuList t)
    {
        List<MenuList> tlist = new ArrayList<MenuList>();
        Iterator<MenuList> it = list.iterator();
        while (it.hasNext())
        {
            MenuList n = (MenuList) it.next();
            if (StringUtils.equals(n.getParentId(),t.getMenuId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    /**
     * 判断是否有子节点
     */
    private static boolean hasChild(List<MenuList> list, MenuList t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
